package Klassen;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
*
* @author eifinger
* @param String
* filename Generates a file with a new Sudoku in csv format.
* Requires Internetconnection.
*/
public class SudokuGetter {
public static String getSudoku(String filename) throws IOException {
System.out.println("Start Connection" + System.currentTimeMillis());
URL url = new URL("http://de1.websudoku.com/?");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String table;
String csv = "";
String result = "";
String field="";
System.out.println("Start Conversion" + System.currentTimeMillis());
while ((table = in.readLine()) != null) {
if (table.contains("AUTOCOMPLETE")) { // Find line containing the
// table
int n = 0;
while (n < 81) {
table = table.substring(table.indexOf("<TD")+3);//Cut line from beginning to first field
field = table.substring(0,table.indexOf("/TD")); //Get one field
if(field.contains("READONLY VALUE=\"")){
csv = csv.concat(field.substring(field.indexOf("READONLY VALUE=\"")+16, field.indexOf("READONLY VALUE=\"")+17));
}else{
csv = csv.concat("0");
}
n++;
}
break;
}
}
result = csv;
System.out.println("End Conversion" + System.currentTimeMillis());
if(filename != null){
File file = new File(filename);
FileWriter fw = new FileWriter(file);
for (int i = 0; i < 9; i++) {
for (int t = 0; t < 9; t++) {
fw.write("\"" + csv.charAt(t) + "\"");
if (t < 8) {
fw.write(",");
}
}
fw.write(System.getProperty("line.separator"));
csv = csv.substring(9);
}
fw.flush();
fw.close();
}
return result;
}
}